package com.zeyun.EasyOnlineShareCloud.utils;

import java.security.SecureRandom;

/**
 * 密码生成工具类
 */
public class PasswordGenerator {

    private static final String CHAR_LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String CHAR_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String DIGIT = "0123456789";
    private static final String SPECIAL = "!@#$%^&*()_+";
    private static final String ALL = CHAR_LOWERCASE + CHAR_UPPERCASE + DIGIT + SPECIAL;
    
    private static final SecureRandom RANDOM = new SecureRandom();

    /**
     * 生成随机密码
     *
     * @param length 密码长度
     * @return 随机密码
     */
    public static String generateRandomPassword(int length) {
        if (length < 8) {
            length = 8; // 最小密码长度为8
        }
        
        StringBuilder password = new StringBuilder(length);
        
        // 确保密码包含至少一个小写字母、一个大写字母、一个数字和一个特殊字符
        password.append(CHAR_LOWERCASE.charAt(RANDOM.nextInt(CHAR_LOWERCASE.length())));
        password.append(CHAR_UPPERCASE.charAt(RANDOM.nextInt(CHAR_UPPERCASE.length())));
        password.append(DIGIT.charAt(RANDOM.nextInt(DIGIT.length())));
        password.append(SPECIAL.charAt(RANDOM.nextInt(SPECIAL.length())));
        
        // 填充剩余长度
        for (int i = 4; i < length; i++) {
            password.append(ALL.charAt(RANDOM.nextInt(ALL.length())));
        }
        
        // 打乱密码顺序
        char[] passwordArray = password.toString().toCharArray();
        for (int i = 0; i < passwordArray.length; i++) {
            int randomIndex = RANDOM.nextInt(passwordArray.length);
            char temp = passwordArray[i];
            passwordArray[i] = passwordArray[randomIndex];
            passwordArray[randomIndex] = temp;
        }
        
        return new String(passwordArray);
    }
    
    /**
     * 生成默认长度(12位)的随机密码
     *
     * @return 随机密码
     */
    public static String generateRandomPassword() {
        return generateRandomPassword(12);
    }

    /* public static void main(String[] args) {
        System.out.println(generateRandomPassword(6));
    } */
}